package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
   @Autowired
   private ShoppingCartMapper shoppingCartMapper;

    @Override
    public R subDe(ShoppingCart shoppingCart) {

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, UserHolder.getUserId());
        wrapper.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        wrapper.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        ShoppingCart shoppingCartDB = shoppingCartMapper.selectOne(wrapper);
        if (shoppingCartDB == null) {
            return R.error("商品未在购物车中");
        }
        shoppingCartDB.setNumber(shoppingCartDB.getNumber() - 1);
        if (shoppingCartDB.getNumber() <= 0) {
            //将该商品从购物车中移除  -- delete删除
            shoppingCartMapper.deleteById(shoppingCartDB.getId());
        } else {
            //确定没有数据了修改正确值
            shoppingCartMapper.updateById(shoppingCartDB);
        }
        return R.success(shoppingCartDB);

    }
}
